#include "thumbnailengine.h"
#include "tools.h"
#include <QDir>
#include <QDateTime>
#include "imageloader.h"

ThumbnailEngine::ThumbnailEngine()
    : m_cache_path(QDir::homePath() + QDir::separator() + ".pio" + QDir::separator() + "cache")
{
    QDir().mkpath(m_cache_path);
}

ThumbnailEngine::~ThumbnailEngine()
{
}

QImage ThumbnailEngine::load(const QString & filename)
{
    // get thumbnail filename
    QString thumbnail_filename = getThumbnailFilename(filename);

    // check if thumbnail exists and is up to date
    QFileInfo fi1(thumbnail_filename);
    QFileInfo fi2(filename);
    if(fi1.exists() && fi1.lastModified().addSecs(2) >= fi2.lastModified())
        return QImage(thumbnail_filename);

    // if thumbnail does not exist or is not up to date, create it...
    QDir().mkpath(fi1.absolutePath());

    ImageLoader loader;
    QImage image = loader.load(filename, QSize(256, 256));
    image.save(thumbnail_filename);
    return image;
}

QString ThumbnailEngine::getThumbnailFilename(const QString &filename)
{
    QByteArray ar = QString("%1:256:256").arg(filename).toLocal8Bit();
    QString hash = tools::hex(tools::sha256(std::basic_string<unsigned char>((unsigned char*)ar.data(), ar.length()))).c_str();
    QString path = m_cache_path + "/" + hash.left(2);
    return path + "/" + hash.mid(2) + ".jpg";
}

//int ThumbnailEngine::orientation(const QString &filename)
//{
//    int orientation = 0;
/**** libexif ****
    ExifLoader * loader = exif_loader_new();
    exif_loader_ref(loader);

    exif_loader_write_file(loader, filename.toLocal8Bit().data());
    ExifData * data = exif_loader_get_data(loader);
    if(data) {
        orientation = tools::orientation(data);
        exif_data_unref(data);
    }
    exif_loader_unref(loader);
*/

/**** libexiv2 **** /
    try {
        Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(filename.toLocal8Bit().data());
        if(image.get()) {
            image->readMetadata();
            Exiv2::ExifData & exif = image->exifData();
            Exiv2::ExifData::iterator orient = exif.findKey(Exiv2::ExifKey("Exif.Image.Orientation"));
            if(orient==exif.end() || orient->toLong()==1)
                orientation = 0;
            else if(orient->toLong()==6)
                orientation = 1;
            else if(orient->toLong()==3)
                orientation = 2;
            else if(orient->toLong()==8)
                orientation = 3;
            else
                orientation = 0;

        }
    }
    catch(std::exception & e) {
        std::cout << e.what() << std::endl;
    }


    return orientation;
}
*/
